%% -*- mode: erlang -*-
IsCentos6 = fun() ->
    case file:read_file("/etc/centos-release") of
        {ok, <<"CentOS release 6", _/binary>>} ->
            true;
        _ ->
            false
    end
end,

IsWin32 = fun() ->
    win32 =:= element(1, os:type())
end,

IsMacOS = fun() ->
    {unix, darwin} =:= os:type()
end,

IsQuicSupp = fun() ->
    not (IsCentos6() orelse IsWin32() orelse
        IsMacOS() orelse
        false =/= os:getenv("BUILD_WITHOUT_QUIC")) orelse
        "1" == os:getenv("BUILD_WITH_QUIC")
end,

Bcrypt = {bcrypt, {git, "https://github.com/emqx/erlang-bcrypt.git", {tag, "0.6.0"}}},
Quicer = {quicer, {git, "https://github.com/emqx/quic.git", {tag, "0.0.111"}}}.

Dialyzer = fun(Config) ->
                   {dialyzer, OldDialyzerConfig} = lists:keyfind(dialyzer, 1, Config),
                   {plt_extra_apps, OldExtra} = lists:keyfind(plt_extra_apps, 1, OldDialyzerConfig),
                   Extra = OldExtra ++ [quicer || IsQuicSupp()],
                   NewDialyzerConfig = [{plt_extra_apps, Extra} | OldDialyzerConfig],
                   lists:keystore(
                     dialyzer,
                     1,
                     Config,
                     {dialyzer, NewDialyzerConfig}
                    )
           end.

ExtraDeps = fun(C) ->
    {deps, Deps0} = lists:keyfind(deps, 1, C),
    {erl_opts, ErlOpts0} = lists:keyfind(erl_opts, 1, C),
    IsQuic = IsQuicSupp(),
    New = [
        {deps, Deps0 ++ [Bcrypt || not IsWin32()] ++ [Quicer || IsQuic]},
        {erl_opts, ErlOpts0 ++ [{d, 'BUILD_WITHOUT_QUIC'} || not IsQuic]}
    ],
    lists:foldl(
        fun({Key, _Val} = KV, Acc) ->
            lists:keystore(Key, 1, Acc, KV)
        end,
        C,
        New
    )
end,

Dialyzer(ExtraDeps(CONFIG)).
